package com.mojo.concurrent.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程实现类
 *
 * @author <a href="mailto:mojo_jj@163.com">Mojo</a>
 */
public class RunnableImpl implements Runnable {
    private int ticket = 100;
    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (ticket > 0) {
                try {
                    Thread.sleep(10);
                    System.out.println(Thread.currentThread().getName() + "买了第" + ticket + "张票");
                    if (ticket == 50) {
                        int n = 1 / 0;
                    }
                    ticket--;
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                } finally {
                    lock.unlock();
                }
                //
            } else {
                lock.unlock();
                break;
            }
        }
        //出现未能捕捉的异常，有其他线程买同一张票，还是有线程安全问题
        //Thread-2买了第50张票
        //Exception in thread "Thread-2" java.lang.ArithmeticException: / by zero
        //at com.mojo.concurrent.lock.RunnableImpl.run(RunnableImpl.java:25)
        //at java.lang.Thread.run(Thread.java:748)
        //Thread-0买了第50张票
        //Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
        //at com.mojo.concurrent.lock.RunnableImpl.run(RunnableImpl.java:25)
        //at java.lang.Thread.run(Thread.java:748)
    }
}
